package com.lianyu507.controller;

import com.lianyu507.bean.PagingProperties;
import com.lianyu507.enums.ErrorTypeEnum;
import com.lianyu507.enums.NormalStatusEnum;
import com.lianyu507.pojo.CrArticle;
import com.lianyu507.pojo.CrArticleExample;
import com.lianyu507.service.CrArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/crArticle")
public class ArticleController extends BaseController {

    @Autowired
    private CrArticleService crArticleService;


    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> insert( @RequestBody CrArticle crArticle) {
        crArticle.setCreateTime(new Date());
        crArticle.setStatus(NormalStatusEnum.NORMAL.getByte());
        crArticleService.insert(crArticle);
        return successResult(crArticle);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") Integer id) {
        CrArticle delete = new CrArticle();
        delete.setId(id);
//        delete.setStatus(NormalStatusEnum.DELETED.getValue());
        crArticleService.updateByPrimaryKeySelective(delete);
        return successResult("Ok");
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> list(PagingProperties paging) {
        CrArticleExample exam = new CrArticleExample();
        if(paging.getNeedPaging()) {
            paging.setTotal(crArticleService.countByExample(exam));
            exam.setOrderByClause(" id desc " + paging.build());
        }
        List<CrArticle> list = crArticleService.selectByExample(exam);
        return successPageList(paging,list);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> get(@PathVariable("id") Integer id) {
        return successResult(crArticleService.selectByPrimaryKey(id));
    }

    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> update(@PathVariable("id") Integer id, @Valid @RequestBody CrArticle crArticle, BindingResult result) {
        if (result.hasErrors()) {
            return failedResult(ErrorTypeEnum.VALIDATE_ERROR, result.getAllErrors().get(0).getDefaultMessage());
        }
        crArticleService.updateByPrimaryKeySelective(crArticle);
        return successResult("ok");
    }

}
